package com.zbf.user.web;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbf.auth.mapper.UserDao;
import com.zbf.common.entity.ExcleEntity;
import com.zbf.common.entity.ResponseResult;
import com.zbf.common.entity.UserEntity;
import com.zbf.common.exception.AllStatusEnum;
import com.zbf.common.utils.PoiUtil;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Configuration;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: wangfa
 * 作者: LCG
 * 日期: 2020/9/7  23:54
 * 描述:
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserDao userDao;


    /**
    * @Author wangfa
    * @Description //TODO 用户列表的展示+模糊+分页
    * @Date 8:54 2020/9/21
    * @Param [current, size, userName, loginName, tel]
    * @return com.zbf.common.entity.ResponseResult
    **/
    @RequestMapping("/userlist")
    public ResponseResult getUserlist(@RequestParam Integer current,@RequestParam Integer size,String userName,String loginName,String tel){
        System.out.println(current+"分页数据"+size);
        System.out.println("模糊查询的数据 用户名"+userName);
        System.out.println("模糊查询的数据 登录名"+loginName);
        System.out.println("模糊查询的数据 电话"+tel);

        ResponseResult responseResult = new ResponseResult();
        Page<UserEntity> page = new Page<UserEntity>(current,size);
        IPage<UserEntity> selectPageVo = userDao.selectPageVo(page,userName,loginName,tel);
        responseResult.setCode(AllStatusEnum.REGIST_SUCCESS.getCode());
        responseResult.setSuccess(AllStatusEnum.REQUEST_SUCCESS.getMsg());
        responseResult.setResult(selectPageVo);
        System.out.println("查询到的user列表数据"+responseResult+selectPageVo);
        return responseResult;
    }

    
    /**
    * @Author wangfa
    * @Description //TODO 添加用户列表的数据
    * @Date 8:54 2020/9/21
    * @Param [user]
    * @return com.zbf.common.entity.ResponseResult
    **/

    @RequestMapping("/userinsert")
    public ResponseResult getUserlist(@RequestBody UserEntity user) throws IOException {
        System.out.println("添加到用户列表的数据"+user);
        boolean b=false;
        if (user.getId()!=null){
             b=userDao.updateUser(user);
        }else{
             b = userDao.addUser(user);
        }
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(AllStatusEnum.REGIST_SUCCESS.getCode());
        responseResult.setSuccess(AllStatusEnum.REQUEST_SUCCESS.getMsg());
        responseResult.setResult(b);

        return responseResult;
    }

    @RequestMapping("/getDoc")
    public ResponseResult getDoc(@RequestBody UserEntity baseUser) throws IOException, TemplateException {
        System.out.println("******baseUser*******"+baseUser);
        ResponseResult responseResult = new ResponseResult();
        try {
            Map<String,String> dataMap = new HashMap<String,String>();
            if(baseUser.getId() != null ){
                dataMap.put("id", String.valueOf(baseUser.getId()));
            }else{
                dataMap.put("id", "该用户没有id");
            }
            if(baseUser.getUserName() != null){
                dataMap.put("userName", baseUser.getUserName());
            }else{
                dataMap.put("userName","该用户没有姓名");
            }
            if(baseUser.getLoginName() != null){
                dataMap.put("loginName", baseUser.getLoginName());
            }else{
                dataMap.put("loginName","该用户没有登录姓名");
            }
            if(baseUser.getSex() != null){
                if (baseUser.getSex()=="1"){
                    dataMap.put("sex", "男");
                }else {
                    dataMap.put("sex", "女");
                }

            }else{
                dataMap.put("sex","该用户没有登录姓名");
            }
            if(baseUser.getEmail() != null){
                dataMap.put("email", baseUser.getEmail());
            }else{
                dataMap.put("email","该用户没有邮箱");
            }
            if(baseUser.getTel() != null ){
                dataMap.put("tel", baseUser.getTel());
            }else{
                dataMap.put("tel","该用户没有手机号");
            }
            if(baseUser.getRolename() != null){
                dataMap.put("rolename", baseUser.getRolename());
            }else{
                dataMap.put("rolename","该用户没有所属角色");
            }
            if (baseUser.getImg()!=null){
                String image = ImageToBase64ByOnline(baseUser.getImg());
                image.substring(image.indexOf(',') + 1);
                dataMap.put("image",image);
            }else{
                dataMap.put("image","该用户没有头像");
            }
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            //指定模板路径的第二种方式
            configuration.setDirectoryForTemplateLoading(new File("D:/doc"));

            // 输出文档路径及名称
            File outFile = new File("D:/doc/"+baseUser.getUserName()+".doc");
            //以utf-8的编码读取ftl文件
            Template t =  configuration.getTemplate("jian7.ftl","utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
            t.process(dataMap, out);
            out.close();
            responseResult.setResult(true);
            return responseResult;
        }catch (Exception e){
            e.printStackTrace();
        }
        responseResult.setResult(false);
        return responseResult;
    }


    //上传图片
    //minio端口号
    private static  String url="http://192.168.12.1:9000";
    //账号密码
    private static  String access="minioadmin";
    private static  String secret="minioadmin";
    //上传文件夹名称
    private static String bucket="wangfa";
    /*
     * @Author wangfa
     * @Description //图片上传
     * @Date  2020/9/20
     * @Param [file]
     * @return java.lang.String
     **/
    @RequestMapping("upload")
    public String upload(@RequestParam("file")MultipartFile file)throws IOException, InvalidPortException, InvalidEndpointException {
        String fileName=null;
        try {
            //创建MinioClient对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(url)
                            .credentials(access, secret)
                            .build();
            InputStream in = file.getInputStream();
            fileName = file.getOriginalFilename();
            //String fileName = file.getName();
            //文件上传到minio上的Name把文件后缀带上，不然下载出现格式问题
            fileName = UUID.randomUUID() +"."+fileName.substring(fileName.lastIndexOf(".") + 1);
            //创建头部信息
            Map<String, String> headers = new HashMap<>(10);
            //添加自定义内容类型
            headers.put("Content-Type", "image/jpeg");
            //添加存储类
            headers.put("X-Amz-Storage-Class", "REDUCED_REDUNDANCY");
            //添加自定义/用户元数据
            Map<String, String> userMetadata = new HashMap<>(10);
            userMetadata.put("My-Project", "Project One");
            //上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucket).object(fileName).stream(
                            in, in.available(), -1)
                            .headers(headers)
                            .build());
            in.close();
            System.out.println(fileName);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        System.out.println(url+"/"+bucket+"/"+fileName);
        return url+"/"+bucket+"/"+fileName;
    }

    //图片上传
    public static String ImageToBase64ByOnline(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }


    @RequestMapping("changerStatus")
    public ResponseResult changerStatus(Long sid,int status){
        System.out.println("激活状态"+status+"激活的id:"+sid);
        if(status==0){
            status=1;
        }else {
            status=0;
        }
        ResponseResult responseResult = new ResponseResult();
        boolean b = userDao.setStatus(status,sid);
        responseResult.setCode(AllStatusEnum.REGIST_SUCCESS.getCode());
        responseResult.setSuccess(AllStatusEnum.REQUEST_SUCCESS.getMsg());
        responseResult.setResult(b);
        return responseResult;
    }



    @RequestMapping("toExcel")
    public ResponseResult toExcel(@RequestBody ExcleEntity excleEntity){
        System.err.println(excleEntity);
        ResponseResult responseResult = ResponseResult.getResponseResult();
        try {
            //通过数据源获取与数据库的连接  没配置spring的可用原生的jdbc来获取连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank?serverTimezone=UTC", "root", "root");
            //查询的sql语句

            //拼接需要查询的字段
            StringBuffer stringBufferSelect = new StringBuffer();
            String types = "";
            if(excleEntity.getType()!=null && excleEntity.getType().length>0){
                types = "";
                for (String type:excleEntity.getType()) {
                    types += type+",";
                }
                stringBufferSelect.append(types.substring(0,types.length()-1));
            }else{
                stringBufferSelect.append("u.*");
            }

            //拼接需要根据什么排序
            StringBuffer stringBufferOrderType = new StringBuffer();
            String orders = "";
            if(excleEntity.getOrderType()!=null && excleEntity.getOrderType().length>0){
                stringBufferOrderType.append("ORDER BY ");
                orders = "";
                if(excleEntity.getOrderType().length>1){
                    for (String order:excleEntity.getOrderType()) {
                        orders += order+" and ";
                    }
                    stringBufferOrderType.append(orders.substring(0,orders.length()-4));
                }else{
                    String[] orderType = excleEntity.getOrderType();
                    stringBufferOrderType.append(orderType[0]);
                }
            }else{
                stringBufferOrderType.append(" ");
            }

            //拼接需要根据什么排序
            StringBuffer stringBufferOrder = new StringBuffer();
            //拼接需要升序还是降序
            if(excleEntity.getOrder()!=null && !("").equals(excleEntity.getOrder())){
                stringBufferOrder.append(" "+excleEntity.getOrder());
            }else{
                stringBufferOrder.append(" ");
            }
            //拼接要导出多少条数据
            StringBuffer stringBufferLimit = new StringBuffer();
            if(excleEntity.getTotal()!=null && excleEntity.getTotal()!=0){
                stringBufferLimit.append(" LIMIT 0,"+excleEntity.getTotal());
            }else{
                stringBufferOrder.append(" ");
            }

            StringBuilder sql=new StringBuilder("select "+stringBufferSelect+" from base_user u LEFT JOIN base_user_role ur on u.id = ur.userId" +
                    " LEFT JOIN base_role r on r.id = ur.roleId GROUP BY u.id "+stringBufferOrderType+stringBufferOrder+stringBufferLimit);

            System.err.println("打印sql=="+sql);
            //生成的excel表的路径   注意文件名要和数据库中表的名称一致  因为导入时要用到。
            String filePath="D:\\excel\\"+excleEntity.getExcleName()+".xls";
            //导出
            PoiUtil.exportToExcel(connection,sql.toString(), "base_user", filePath);
            responseResult.setCode(200);
            responseResult.setSuccess("导出excel成功");
            return responseResult;
        }catch (Exception x){
            x.printStackTrace();
            responseResult.setCode(500);
            responseResult.setSuccess("导出excel失败");
            return responseResult;
        }
    }


    @RequestMapping("bindRoleForUser")
    public ResponseResult bindRoleForUser(@RequestParam Long id,@RequestParam String ids[]){
        System.out.println("绑定角色传回来的用户id"+id+"角色id数组:"+ids);
        for (int i=0;i<ids.length;i++){
            System.out.println("绑定角色传回后台的数组:"+ids[i]);
        }
        userDao.deleteUserRole(id);
        boolean b=false;
        try {
            for (int i=0;i<ids.length;i++){
               if (ids[i]=="1" ||ids[i]=="2" || ids[i]=="3" ){
                   userDao.setRolefoUser(id,Long.valueOf(ids[i]));
               }else {
                   Long rid=userDao.selectRoleid(ids[i]);
                   System.err.println("根据角色查询到的id:"+rid);
                   if(rid!=null){
                       userDao.setRolefoUser(id,rid);
                   }
               }
            }
            b=true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(AllStatusEnum.REGIST_SUCCESS.getCode());
        responseResult.setSuccess(AllStatusEnum.REQUEST_SUCCESS.getMsg());
        responseResult.setResult(b);
        return responseResult;
    }







}
